// jwt.js,token中间件
const jwt = require('jsonwebtoken');
const expressJwt = require("express-jwt");
const { secretKey } = require('./constant');
// express-jwt中间件帮我们自动做了token的验证以及错误处理，所以一般情况下我们按照格式书写就没问题，其中unless放的就是你想要不检验token的api。
const jwtAuth = expressJwt(
    {
        secret: secretKey,
        getToken: function fromHeaderOrQuerystring (req) {
            if (req.headers.authorization) {
                return req.headers.authorization;
            } else if (req.query && req.query.token) {
                return req.query.token;
            }
            return null;
        }
    }).unless({path: ["/users/login", "/users/register", /\/api\/.*\/image\/.*/]});

jwtAuth.signObject = function(obj){
    return jwt.sign(obj, secretKey, {
        expiresIn : 60 * 60 * 24 // 授权时效24小时
    });
}
module.exports = jwtAuth;
